from django.shortcuts import render,redirect,reverse
import string
from django.http.response import JsonResponse
from .models import CaptchaModel, UserActivity
# Create your views here.
import random
from django.core.mail import send_mail
from django.views.decorators.http import require_http_methods,require_POST,require_GET
from .forms import RegisterForm,LoginForm,PubBlogForm
from django.contrib.auth import get_user_model,login,logout
from django.urls.base import reverse_lazy
from django.contrib.auth.decorators import login_required
from .models import BlogCategory, Blog,BlogComment
from django.db.models import Q

# TODO 生产环境时打开csrf验证
from django.views.decorators.csrf import csrf_exempt
# from django.contrib.auth.models import User
# 13680972988@163.com
User = get_user_model()


def index(request):
    """博客首页"""
    blogs = Blog.objects.all()
    try:

        # user = User.objects.filter(email='88882345678@163.com').first()
        # print(user)

        user_id = request.user.id

    except Exception as e:
        user_id = 1
    return render(request, 'blog_index.html', context={'blogs': blogs, 'user_id':user_id})


@require_http_methods(['GET', 'POST'])
@csrf_exempt
def blog_login(request):
    """博客登录功能实现"""
    if request.method == 'GET':
        return render(request, 'blog_login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            # User.is_authenticated = True
            # request.session['user id']='solitary'
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request, user)
                print('login success')
                # User.is_authenticated
            # login(request, user)
            # 判断是否需要记住我
                if not remember:
                    request.session.set_expiry(0)
                return redirect(reverse('bootstrapApp:index'))
                 # 如果点击了，那么就什么都不做，使用默认的2周的过期时间
            print('login fail')
            return redirect(reverse('bootstrapApp:blog_login'))
        else:
            # 如果没有点击记住我，那么就要设置过期时间为0，即测览器关闭后就会过期
            print('邮箱或密码错误!')
            # form.add_error('email'，'邮箱或者密码错误!')
            # return render(request,"login.html',context={"form": form})
            return redirect(reverse('bootstrapApp:blog_login'))


def blog_detail(request, blog_id):
    """查看已发布的博客功能实现"""
    try:
        blog = Blog.objects.get(pk=blog_id)
    except Exception as e:
        blog = None
    return render(request,'blog_detail.html', context = {'blog': blog})

# 博客发布功能
@require_http_methods(['GET', 'POST'])
@login_required(login_url=reverse_lazy('bootstrapApp:blog_login'))
@csrf_exempt
def blog_pub(request):
    """博客发布功能实现 加了login_required需要登录 否则跳转登录"""
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, 'blog_pub.html', context={"categories": categories})
    else:
        form = PubBlogForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            blog = Blog.objects.create(title=title, content=content, category_id=category_id, author=request.user)
            return JsonResponse({"code": 200,"message": "博客发布成功!","data":{"blog_id":blog.id}})
        else:
            print(form.errors)
            return JsonResponse({'code': 400,"message": "参数错误!"})

# 博客注册功能实现
@require_http_methods(['GET', 'POST'])
def blog_register(request):
    """博客注册功能实现"""
    if request.method == 'GET':
        return render(request,'blog_register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            User.objects.create_user(email=email,username=username, password=password)
            return redirect(reverse('bootstrapApp:blog_login'))
        else:
            print(form.errors)
            # 重新跳转到登录页面
            return render(request, 'blog_register.html', {'form': form})
            # return render(request,'register.html',context={"form": form})

# 发送验证码功能 还需要对验证码做一个过期处理
def send_email_captcha(request):
    """发送验证码功能实现"""
    # ?email=xxX
    email = request.GET.get('email')
    if not email:
        return JsonResponse({"code":"400","message":"必须传递邮箱!"})
    #生成验证码(取随机的4位阿拉伯数字)
    captcha ="".join(random.sample(string.digits, 4))
    print(captcha)
    CaptchaModel.objects.update_or_create(email=email,defaults={'captcha': captcha})
    send_mail("ttt博客注册验证码",message=f"您的注册验证码是:{captcha}",recipient_list=[email],from_email=None)
    return JsonResponse({"code":200,"message":"邮箱验证码发送成功!"})

# 博客点击退出功能实现
def blog_logout(request):
    """博客退出功能实现"""
    logout(request)
    return redirect('bootstrapApp:index')

@require_POST
@login_required(login_url=reverse_lazy('bootstrapApp:blog_login'))
def pub_comment(request):
    """发布评论"""
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    BlogComment.objects.create(content=content, blog_id=blog_id, author=request.user)
    return redirect(reverse("bootstrapApp:blog_detail", kwargs = {'blog_id': blog_id}))


from django.core.cache import cache
from django.views.decorators.http import require_GET
from django.shortcuts import render
from django.db.models import Q
from .models import Blog
import json
from datetime import timedelta


@require_GET
def search(request):
    """搜索模块 会按下面的url格式传参"""
    # /search?q=xxx
    q = request.GET.get('q')

    # 如果搜索词为空，返回空结果
    if not q:
        return render(request, 'blog_index.html', context={"blogs": []})

    # 创建基于搜索词的缓存键
    cache_key = f"search_results:{q.lower()}"

    # 尝试从Redis缓存获取结果
    cached_results = cache.get(cache_key)

    if cached_results is not None:
        # 如果缓存存在，直接使用缓存的结果
        # 这里我们存储的是博客ID列表，需要从数据库获取完整对象
        blog_ids = json.loads(cached_results)
        blogs = Blog.objects.filter(id__in=blog_ids).order_by('-created_at')
    else:
        # 如果缓存不存在，执行数据库查询
        blogs = Blog.objects.filter(
            Q(title__icontains=q) | Q(content__icontains=q)
        ).order_by('-created_at')

        # 将结果缓存到Redis，存储ID列表而不是完整对象
        blog_ids = list(blogs.values_list('id', flat=True))
        cache.set(
            cache_key,
            json.dumps(blog_ids),
            timeout=300  # 缓存5分钟，根据需求调整
        )

    return render(request, 'blog_index.html', context={"blogs": blogs})


@login_required(login_url=reverse_lazy('bootstrapApp:blog_login'))
def blog_myself(request, user_id):
    """我的 仿发布写法传参 需要用户登录 否则跳转登录"""
    try:
        user_myself = User.objects.get(id=user_id)
        user_myself_profile = None
        blogs = Blog.objects.filter(author=user_id).all()
    except Exception as e:
        print("找不到")
        user_myself = None
        user_myself_profile = None
        blogs = None
    # return render(request,'blog_detail.html', context = {'blog': blog})
    return render(request,'blog_myself.html',
                  context = {'user_myself': user_myself,
                             'user_myself_profile':user_myself_profile,
                             'blogs' : blogs})

def blog_myself_to_myBlogs(request,user_id):
    try:
        blogs = Blog.objects.filter(author=user_id).all()
    except Exception as e:
        print(e)
        print("找不到2")
        blogs = None
    return render(request,'blog_index.html', context={"blogs": blogs})

@require_http_methods(['GET', 'POST'])
@login_required(login_url=reverse_lazy('bootstrapApp:blog_login'))
def blog_informationChange(request,user_id):
    """用户修改自定义信息功能实现"""
    if request.method == 'GET':
        try:
            user_myself = User.objects.get(id=user_id)
            user_myself_profile = None
        except Exception as e:
            print("找不到")
            user_myself = None
            user_myself_profile = None
        # return render(request,'blog_detail.html', context = {'blog': blog})
        return render(request, 'blog_informationChange.html',
                      context={'user_myself': user_myself, 'user_myself_profile': user_myself_profile})
    else:
        pass

def blog_dialogue(request):
    """与他人对话"""
    return render(request,'blog_dialogue.html')

# views.py
# from django.db.models import Count
# from django.contrib.auth.decorators import login_required
#
# @login_required
# def my_profile(request):
#     # 统计信息
#     stats = {
#         'blog_count': request.user.blogs.count(),
#         'comment_count': request.user.comments.count(),
#         'follower_count': request.user.followers.count(),
#         'following_count': request.user.following.count(),
#     }
#
#     # 最近活动
#     recent_activities = request.user.activities.all()[:10]
#
#     # 未读消息
#     unread_messages = request.user.messages.filter(status='unread')
#
#     context = {
#         'stats': stats,
#         'recent_activities': recent_activities,
#         'unread_messages': unread_messages,
#     }
#     return render(request, 'blog_myself.html', context)
#
# # signals.py
# from django.db.models.signals import post_save
# from django.dispatch import receiver
# from .models import Blog, BlogComment
#
# @receiver(post_save, sender=Blog)
# def create_blog_activity(sender, instance, created, **kwargs):
#     if created:
#         UserActivity.objects.create(
#             user=instance.author,
#             activity_type='blog_publish',
#             content=f'发布了新博客《{instance.title}》',
#             metadata={'blog_id': instance.id}
#         )
#
# @receiver(post_save, sender=BlogComment)
# def create_comment_activity(sender, instance, created, **kwargs):
#     if created:
#         UserActivity.objects.create(
#             user=instance.user,
#             activity_type='comment_post',
#             content=f'评论了博客《{instance.blog.title}》',
#             metadata={'blog_id': instance.blog.id, 'comment_id': instance.id}
#         )

def blog_test(request):
    return render(request,'blog_test.html')

@login_required(login_url=reverse_lazy('bootstrapApp:blog_login'))
def blog_test2(request, user_id):
    """我的 仿发布写法传参 需要用户登录 否则跳转登录"""
    try:
        user_myself = User.objects.get(id=user_id)
        user_myself_profile = None
        blogs = Blog.objects.filter(author=user_id).all()
    except Exception as e:
        print("找不到")
        user_myself = None
        user_myself_profile = None
        blogs = None
    # return render(request,'blog_detail.html', context = {'blog': blog})
    return render(request,'blog_test2.html',
                  context = {'user_myself': user_myself,
                             'user_myself_profile':user_myself_profile,
                             'blogs' : blogs})

